package com.wu.service.impl;


import com.wu.dao.CounterDao;
import com.wu.pojo.po.paperPo.Counter;
import com.wu.pojo.vo.DataVo;
import com.wu.service.CounterService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.List;

public class CounterServiceImpl implements CounterService{

    @Autowired
    private CounterDao counterDao;

    @Transactional
    @Override
    public int insertCounter(Counter counter) {
        return counterDao.insertCounter(counter);
    }


    @Override
    public int queryByPaperIdAndUserId(String paperId, String userId) {
        return counterDao.queryByPaperIdAndUserId(paperId, userId);
    }

    @Override
    public JSONObject initData(List<DataVo> dataVos) {

        // 分析数据
        double totalRunningIndex = 0;
        double totalWeight = 0;
        for (DataVo view : dataVos) {// 计算模型总权重值
            int weight = view.getWeightValue();
            totalWeight += weight;
        }
        JSONArray indexArray = new JSONArray();
        JSONArray nameArray = new JSONArray();
        JSONObject nameObject = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        for (DataVo view : dataVos) {
            int weight = view.getWeightValue();
            double avgScore = view.getAvgScore();
            String title = view.getTitle();
            // 权重计算最终分值
            totalRunningIndex += weight * avgScore;

            DecimalFormat df =new DecimalFormat("#.00");
            String avgScoreF = df.format(avgScore);

            // 参数格式化，匹配echart格式
            nameObject.put("name",title);// 设置echart雷达图顶点描述
            nameObject.put("max",100);// 设置echart雷达图最大值
            nameArray.add(nameObject);
            indexArray.add(avgScoreF);// echart雷达图对应值
        }

        double runningIndex = 0;// 计算最终运行指数
        try {
            runningIndex = totalRunningIndex / totalWeight;
        } catch (Exception e) {
            throw new RuntimeException("该模型未设置权重信息",e);
        }
        DecimalFormat df =new DecimalFormat("#.00");
        String runningIndexF = df.format(runningIndex);

        jsonObject.put("runningIndex",runningIndexF); //保留两位小数
        jsonObject.put("indexList",indexArray);
        jsonObject.put("nameList",nameArray);

        return jsonObject;
    }

    /**
     * 获取运行指数列表（排名）
     * @return
     */
    @Override
    public List<DataVo> dataRank(DataVo dataVo) {
        return counterDao.dataRank(dataVo);
    }

    @Override
    public DataVo dataRankByUserId(String userId) {
        return counterDao.dataRankByUserId(userId);
    }
}
